package com.ihome.android.academy;

import java.io.File;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ihome.android.EAActivity;
import com.ihome.android.EAApp;
import com.ihome.android.analytic.JsonAnalytic;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.common.ComParams;
import com.ihome.android.common.ConfigUtil;
import com.ihome.android.dl.core.DownloadHelper;
import com.ihome.android.dl.core.DownloadTask;
import com.ihome.android.dl.util.DLFileInfo;
import com.ihome.android.dl.util.DownloadValues;
import com.ihome.android.http.HttpActions;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.market2.asynctask.CheckMarketUpdateTask;
import com.ihome.android.market2.asynctask.HomepagecontentTaskEdu;
import com.ihome.android.market2.info.CategoryInfo;
import com.ihome.android.market2.info.TemplateContentInfo;
import com.ihome.android.market2.info.WelcomeInfo;
import com.ihome.android.market2.view.DialogFactory;
import com.ihome.android.market2.view.DialogFactory.onBtnClickListener;
import com.ihome.android.market2.view.gif.GifListener;
import com.ihome.android.market2.view.gif.GifView;
import com.ihome.android.mod.LoginMod;
import com.ihome.android.util.FileUtils;
import com.ihome.android.util.ImageHelper;
import com.ihome.android.util.SPMgr;
import com.ihome.android.util.Tools;
import com.ihome.android.util.Util;
import com.ihome.android.util.exception.ITVException;
import com.ihome.android.util.log.LogUtil;

@SuppressLint("HandlerLeak")
public class InitialActivity extends EAActivity implements GifListener {
	private final String	TAG								= InitialActivity.class.getSimpleName();
	private WelcomeInfo		welcomInfo;

	@EAInjectView(id = R.id.rl_ad)
	private RelativeLayout	rl_ad;
	@EAInjectView(id = R.id.gif_ad)
	private GifView			gif_ad;
	@EAInjectView(id = R.id.iv_ad)
	private ImageView		iv_ad;

	@EAInjectView(id = R.id.tv_version)
	private TextView		tv_version;

	private Bitmap			bitmapAD;

	private boolean			PRE_INIT_RECOMM_DATA_COMPLETED	= false;

	private final int		AD_END							= 0x122;
	private final int		INIT_FINISH						= 0x123;
	private final int		APK_END							= 0x124;
	private final int		MSG_CHECK_UPDATE				= 0x125;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		LogUtil.d(TAG, "screen :" + dm.widthPixels + " * " + dm.heightPixels + "  " + dm.densityDpi);
		EAApp.getApp().addHandler(mLoadingHandler);
		initArea();

		tv_version.setText(getString(R.string.version_info, Util.getAPKVersion(getApplicationContext())));
	}

	private void initArea() {
		String areaCode = SPMgr.getInstance(getApplicationContext()).getElement(HttpKeys.KEY_AREANO, "");
		if (TextUtils.isEmpty(areaCode)) {
			SharedPreferences sharePre = getSharedPreferences("ottParam", Context.MODE_WORLD_READABLE);
			areaCode = sharePre.getString(HttpKeys.KEY_AREANO, "320000");
			String area = "";

			String[] areaArray = getResources().getStringArray(R.array.province_item);
			String[] areaCodeArray = getResources().getStringArray(R.array.province_item_standard_code);
			for (int i = 0; i < areaCodeArray.length; i++) {
				if (areaCodeArray[i].equals(areaCode)) {
					area = areaArray[i];
					break;
				}
			}
			LogUtil.v(TAG, " initArea()  ---> areaCode = " + areaCode);
			SPMgr.getInstance(getApplicationContext()).putElement(HttpKeys.KEY_AREA, area);
			SPMgr.getInstance(getApplicationContext()).putElement(HttpKeys.KEY_AREANO, areaCode);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		checkNetwork();
	}

	@Override
	public void finish() {
		super.finish();
		EAApp.getApp().clearHandler(mLoadingHandler);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		iv_ad.setImageBitmap(null);
		if (null != bitmapAD && !bitmapAD.isRecycled()) {
			bitmapAD.recycle();
			bitmapAD = null;
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();

		exitApp();
	}

	private void checkNetwork() {

		LogUtil.v(TAG, "isNetworkAvailable = " + Util.isNetworkAvailable(InitialActivity.this));
		if (!Util.isNetworkAvailable(InitialActivity.this)) {

			new DialogFactory(this).showDialog(getString(R.string.attention_error), getString(R.string.check_current_network), "", new onBtnClickListener() {

				@Override
				public void btnRightClickListener(View v) {
					InitialActivity.this.finish();
				}

				@Override
				public void btnNeutralClickListener(View v) {
					InitialActivity.this.finish();
				}

				@Override
				public void btnLeftClickListener(View v) {
					InitialActivity.this.finish();
				}

				@Override
				public void btnCloseClickListener(View v) {
					InitialActivity.this.finish();
				}
			});
			return;
		}
//		mLoadingHandler.sendEmptyMessage(MSG_CHECK_UPDATE);
		//获取数据
		new HomepagecontentTaskEdu(InitialActivity.this).execute();
	}

	private void checkMarketUpdate() {
		JSONArray element = new JSONArray();
		JSONObject item = new JSONObject();
		try {
			item.put("pkgName", getApplicationContext().getPackageName());
			item.put("version", Util.getAPKVersion(InitialActivity.this));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		LogUtil.v(TAG, "checkMarketUpdate item-->" + item.toString());
		if (!TextUtils.isEmpty(item.optString("pkgName")) && !TextUtils.isEmpty(item.optString("version"))) {
			element.put(item);
			new CheckMarketUpdateTask(InitialActivity.this).execute(element.toString());
		}
	}

	public void toLogin() {
		//清空之前的用户注册信息，转为根据ClientID自动注册
		if (!TextUtils.isEmpty(Util.getUserName(this.getApplicationContext()))) {
			SharedPreferences sp = getSharedPreferences(ComParams.SP_NAME_MAIN, Context.MODE_PRIVATE);
			sp.edit().clear().commit();
			LogUtil.d(TAG, "Clear all old user infomation ;");
		}

		if (!TextUtils.isEmpty(Util.getOTTUserName(this.getApplicationContext()))) {
			LoginMod.autoLogin(this);
		}
		else {
			LoginMod.autoRegister(this, "", false);
		}
	}
	
	public void getDataToMain(){
		mLoadingHandler.sendEmptyMessage(AD_END);
	}

	private Handler	mLoadingHandler	= new Handler() {
										@Override
										public void handleMessage(Message msg) {
											super.handleMessage(msg);
											DownloadTask task = null;
											if (msg.obj instanceof DownloadTask) {
												task = (DownloadTask) msg.obj;
											}

											switch (msg.what) {
											case DownloadValues.Types.ADD:
												LogUtil.d(TAG, "---procHandler() Types.ADD ----> FileName = " + task.getAppInfo().getFileName());
												break;

											case DownloadValues.Types.COMPLETE:
												LogUtil.d(TAG, "---procHandler() Types.COMPLETE ----> FileName = " + task.getAppInfo().getFileName());
												handleCompletedAction(task.getAppInfo());
												break;

											case DownloadValues.Types.PROCESS:
												String speed = task.getDownloadSpeed() + "kbps | " + Tools.formateFileSize(getApplication(), task.getDownloadSize()) + " / "
														+ Tools.formateFileSize(getApplication(), task.getTotalSize());
												String progress = task.getDownloadPercent() + "";
												LogUtil.d(TAG, "---procHandler() Types.PROCESS ---->  " + task.getAppInfo().getFileName() + "  ---> speed = " + speed + "; progress = " + progress);
												handleProgress(task.getAppInfo());
												break;
											case AD_END:
												LogUtil.d(TAG, "--- AD_END ----");
//												if (PRE_INIT_RECOMM_DATA_COMPLETED) {
//													sendEmptyMessage(INIT_FINISH);
//												}
//												else {
//													sendEmptyMessageDelayed(AD_END, 500);
//												}
												sendEmptyMessage(INIT_FINISH);
												break;
											case INIT_FINISH:
												LogUtil.d(TAG, "--- AD_END ----");
												removeMessages(AD_END);
												Intent intent = new Intent(InitialActivity.this, MainActivity.class);
												startActivity(intent);
												finish();
												break;
											case APK_END:
												finish();
												break;
											case MSG_CHECK_UPDATE:
												checkMarketUpdate();
												break;
											}
										}
									};

	/**
	 * 文件下载完成
	 * 
	 * @param dLFileInfo
	 * @see [类、类#方法、类#成员]
	 */
	private void handleCompletedAction(DLFileInfo dLFileInfo) {
		LogUtil.d(TAG, "handleCompletedAction()--> IMG = " + (dLFileInfo.getFilePath() + dLFileInfo.getFileName()));

//		if(dLFileInfo.getFileName().toLowerCase().endsWith(".apk")){
//			mLoadingHandler.sendEmptyMessage(APK_END);
//		}else{
//			String filePath = dLFileInfo.getFilePath() + dLFileInfo.getFileName();
//			if ((dLFileInfo.getFileName().toLowerCase().endsWith(".png") || dLFileInfo.getFileName().toLowerCase().endsWith(".jpg")) && FileUtils.isImg(filePath)) {
//				showStaticPic(filePath);
//			}
//			else if ((dLFileInfo.getFileName().toLowerCase().endsWith(".gif")) && FileUtils.isGif(filePath)) {
//				showGifPic(filePath);
//			}
//			mLoadingHandler.sendEmptyMessageDelayed(AD_END, welcomInfo.getWelDuration() * 1000);
//		}
		mLoadingHandler.sendEmptyMessage(AD_END);
	}

	/**
	 * 展现静态图片
	 * 
	 */
	private void showStaticPic(String picPath) {
		LogUtil.d(TAG, "showStaticPic() --> picPath = " + picPath);
		rl_ad.setVisibility(View.VISIBLE);
		iv_ad.setVisibility(View.VISIBLE);
		gif_ad.setVisibility(View.GONE);
		iv_ad.setTag(picPath);

		bitmapAD = ImageHelper.decodeFile(new File(picPath));
		iv_ad.setImageBitmap(bitmapAD);
	}

	/**
	 * 展现Gif图片
	 * 
	 */
	private void showGifPic(String gifPath) {
		LogUtil.d(TAG, "showGifPic() --> gifPath = " + gifPath);
		rl_ad.setVisibility(View.VISIBLE);
		gif_ad.setVisibility(View.VISIBLE);
		gif_ad.setGifImage(gifPath);
		gif_ad.setLoopNumber(2);
		gif_ad.setListener(this, 2);
	}

	@Override
	public void gifEnd(int num) {
		LogUtil.d(TAG, "gifEnd() --> " + "num = " + num);
	}

	@Override
	public void frameCount(int frame) {
		LogUtil.d(TAG, "frameCount() --> frame = " + frame);
		if (frame > 0) {
			if (iv_ad.getVisibility() == View.VISIBLE)
				iv_ad.setVisibility(View.GONE);

			rl_ad.setVisibility(View.VISIBLE);
		}
		else {
			rl_ad.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * 
	 * 根据下载后台服务，更新当前apk下载进度
	 * 
	 * @param dLFileInfo
	 * @param speed
	 * @param progress
	 * @see [类、类#方法、类#成员]
	 */
	private void handleProgress(DLFileInfo dLFileInfo) {}

	/**
	 * 增加下载任务
	 */
	private void addDLFile(DLFileInfo dLFileInfo) {
		DownloadHelper.addNewTask(InitialActivity.this, dLFileInfo, new DownloadHelper.PreDownloadStatusListener() {

			@Override
			public void sdCardCannotWriteOrRead(int errorCode, String errorInfo) {
				Toast.makeText(InitialActivity.this, "不能读写SD卡", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void notFoundSDCard(int errorCode, String errorInfo) {
				Toast.makeText(InitialActivity.this, "没有SD卡", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void moreTaskCount(int errorCode, String errorInfo) {
				Toast.makeText(InitialActivity.this, "任务列表已满", Toast.LENGTH_SHORT).show();
			}
		});
	}

	public void startInitAD(String imgPath) {
		if (!TextUtils.isEmpty(imgPath)) {
			String type = imgPath.substring(imgPath.lastIndexOf(".")+1);
			DLFileInfo picFileInfo = new DLFileInfo();
			picFileInfo.setFilePath(ConfigUtil.FILE_PATH);
			picFileInfo.setFileUrl(imgPath);
			picFileInfo.setFileType(type);
			picFileInfo.setFileName("bg." + type);
			picFileInfo.setIconUrl(imgPath);
			addDLFile(picFileInfo);
		}else{
			mLoadingHandler.sendEmptyMessage(AD_END);
		}
	}

}
